package com.czmh.etc.onlinepubsys.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.czmh.etc.onlinepubsys.constants.GlobalStatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
/**
 * @描述：阿里短信服务工具类
 * @author： Seven.
 * @创建日期：Jun 11, 2019 4:50:51 PM.
 * @版本：1.0.0
 */
@Component
public class AliSmsUtil {
    private static Logger logger = LoggerFactory.getLogger(AliSmsUtil.class);

    @Value("${aliyunsdk.sms.AccessKeyId}")
    private String        AccessKeyId;
    @Value("${aliyunsdk.sms.AccessKeySecret}")
    private String        AccessKeySecret;
    @Value("${aliyunsdk.sms.SignName}")
    private String        SignName;
    @Value("${aliyunsdk.sms.TemplateCode}")
    private String        TemplateCode;
    @Value("${code.sendMsg}")
    private Boolean       open;

    private static String signName;
    private static String templateCode;
    private static String accessKeyId;
    private static String accessKeySecret;
    private static RedisUtil redisUtil;
    private static Boolean smsopen;

    @Autowired
    private RedisUtil RedisUtil;

    /**
    *
    * 先把yml值读取到普通属性中再转到静态属性值时面
    * @PostConstruct修饰的方法会在服务器加载Servlet的时候运行，并且只会被服务器调用一次;
    *
    */
   @PostConstruct
   public void transValues() {
       signName = this.SignName;
       templateCode = this.TemplateCode;
       accessKeyId = this.AccessKeyId;
       accessKeySecret = this.AccessKeySecret;
       redisUtil = this.RedisUtil;
       smsopen = this.open;
   }

    /**
     * 发送手机验证码
     * @param phone  手机号
     * @return 返回：
     */
    public static String sendPhoneVerificationcode(String phone) {
        String code = GenerateCodeUtil.generateValidCode(6);
        //真实验证码,用于生产环境
        if (smsopen) {
            if (redisUtil.hasKey(phone)) {
                code = redisUtil.get(phone).toString();
            }
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            IAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.setMethod(MethodType.POST);
            request.setDomain("dysmsapi.aliyuncs.com");
            request.setVersion("2017-05-25");
            request.setAction("SendSms");
            request.putBodyParameter("PhoneNumbers", phone);
            request.putBodyParameter("TemplateCode", templateCode);
            request.putBodyParameter("SignName", signName);
            request.putBodyParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
            try {
                CommonResponse response = client.getCommonResponse(request);
                String data = response.getData();
                logger.info("【发送结果返回信息】：" + data);
                JSONObject jsonObject = JSONObject.parseObject(data);
                String Code = jsonObject.getString("Code");
                if ("OK".equals(Code)) {
                    // 将验证码存入redis
                    redisUtil.set(phone, code, 60);
                    return GlobalStatusCode.SUCCESS;
                } else {
                    logger.info("发送失败结果:{}", jsonObject);
                    return GlobalStatusCode.FAILED;
                }
            } catch (Exception e) {
                logger.error("发送失败", e);
            }
            return GlobalStatusCode.FAILED;
        } else {
            // 测试情况下固定验证码111111
            code = "111111";
            redisUtil.set(phone, code, 60);
            return code;
        }
    }
}
